package a.a;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class SwapableListViewActivity extends Activity implements SwapableListView.OnItemSwappedListener, OnItemClickListener {
	static final String[] NAMES = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K" };
	private SwapableListView mListView;
	private ArrayAdapter<String> adapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.selectable_list_view_activity);

		mListView = (SwapableListView) findViewById(R.id.listView);
		mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		mListView.setOnItemSwapListener(this);
		mListView.setOnItemClickListener(this);

		adapter = new ArrayAdapter<String>(this, R.layout.select_dialog_singlechoice, R.id.text1, NAMES);
		mListView.setAdapter(adapter);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "up");
		menu.add(0, 1, 0, "down");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			if (mListView.getCheckedItemPosition() != ListView.INVALID_POSITION) {
				int abovePos = mListView.getCheckedItemPosition() - 1;
				if (0 <= abovePos) {
					mListView.swapPositioin(mListView.getCheckedItemPosition(), abovePos);
					mListView.setItemChecked(abovePos, true);
					mListView.smoothScrollToPosition(abovePos);
				}
			}
			break;
		case 1:
			if (mListView.getCheckedItemPosition() != ListView.INVALID_POSITION) {
				int belowPos = mListView.getCheckedItemPosition() + 1;
				if (belowPos < mListView.getCount()) {
					mListView.swapPositioin(mListView.getCheckedItemPosition(), belowPos);
					mListView.setItemChecked(belowPos, true);
					mListView.smoothScrollToPosition(belowPos);
				}
			}
		}
		print();
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onItemSwapped(ListView l, Object item1, Object item2) {
		Log.d("TAG", String.format("onChangedPosition()%s >> %s", item1, item2));
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		mListView.setItemChecked(position, true);
		print();

	}

	private void print() {

		Log.d("TAG", "--<items>--");
		for (int i = 0; i < adapter.getCount(); i++) {
			Log.d("TAG", "print():" + mListView.getItemIdAtPosition(i) + ", " + mListView.getItemAtPosition(i));
		}

	}
}